package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CarListAdapter;
import com.example.administrator.yanfoxconn.adapter.KMDMTBoxAdapter;
import com.example.administrator.yanfoxconn.bean.KMDMT;
import com.example.administrator.yanfoxconn.bean.KNZWGreen;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 總務-綠化管理 項目維護及提交
 * @Author song
 * @Date 11/25/21 4:17 PM
 */
public class KNGreenUpProjectActivity extends BaseActivity implements View.OnClickListener{
    private final int MESSAGE_GREEN_PROJECT = 111;//請求成功
    private KNGreenUpProjectActivity mContext = this;
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTittle;//標題
    @BindView(R.id.btn_title_right)
    Button btnUp;

    @BindView(R.id.lv_list)
    MyListView myListView;

    private List<KNZWGreen> knArea;
    private String result="";
    private String url;
    private String gId;
    private String project,gName;

    private List<KNZWGreen> list;
    private Map<String,String> checkList= new HashMap<String,String>();;
    private KMDMTBoxAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_km_dmt_list);
        ButterKnife.bind(this);
        btnBack.setOnClickListener(this);
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setText("提交");
        btnUp.setOnClickListener(this);
        gId = getIntent().getStringExtra("gId");
        project=getIntent().getStringExtra("project");
        gName=getIntent().getStringExtra("gName");

        tvTittle.setText(project);
        list = new ArrayList<KNZWGreen>();
        getList();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_title_right:
                upCheck();
                break;
        }
    }
    /**
     * 獲取苗木
     */
    private void getList() {
        showDialog();
        String pro = null;
        try {
            pro = URLEncoder.encode(URLEncoder.encode(project, "UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url = Constants.HTTP_GREEN_COURSE + "?gId="+gId+"&project="+pro;
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);

                Log.e("---------", "=getcarLog=fff===" + url);
                Gson gson = new Gson();
                String response = result;

                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        list = new ArrayList<KNZWGreen>();
                        for (JsonElement type : array) {
                            KNZWGreen humi = gson.fromJson(type, KNZWGreen.class);
                            list.add(humi);
                        }
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_TOAST;
                    message.obj = "網絡問題請求失敗,請重試!";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();
    }
    private String ids;//获取ID用于上传
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MESSAGE_TOAST://Toast彈出
//                    ToastUtils.showLong(mContext, msg.obj.toString());
                    myListView.setVisibility(View.VISIBLE);
                    // 适配
                    adapter = new KMDMTBoxAdapter(list, mContext,"kn");
                    myListView.setAdapter(adapter);

                    setListViewHeightBasedOnChildren(myListView);
                    // 绑定listView的监听器
                    myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                long arg3) {
                            // TODO Auto-generated method stub
                            // 取得ViewHolder对象
                            KMDMTBoxAdapter.ViewHolder viewHolder = (KMDMTBoxAdapter.ViewHolder) arg1.getTag();
                            // 改变CheckBox的状态
                            viewHolder.checkBox.toggle();
                            // 将CheckBox的选中状况记录下来
                            list.get(arg2).setBo(viewHolder.checkBox.isChecked());

                            // 调整选定条目
                            if (viewHolder.checkBox.isChecked() == true) {
                   Log.e("---------","checkList=checkList.size()+"+checkList.size()+"+=="+list.get(arg2).getGcId());
//                    pric += Integer.parseInt(list.get(arg2).getName());
                                checkList.put(list.get(arg2).getGcId(),list.get(arg2).getGcName()+"-"+list.get(arg2).getCycleId()+"-"+list.get(arg2).getCycle());
;
                            } else {

//                    pric -= Integer.parseInt(list.get(arg2).getName());
                                checkList.remove(list.get(arg2).getGcId());
                            }
                            // 用TextView显示
//                price.setText("一共选了" + num + "件," + "价格是" + pric + "元");
                        }
                    });
                    break;
                case Constants.MESSAGE_UP://t提交提示
                    ToastUtils.showLong(mContext, msg.obj.toString());
                    finish();
                    break;
                case Constants.MESSAGE_NOT_NET://t提交提示
                    ToastUtils.showLong(mContext, R.string.net_mistake);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    //提交前檢查
    private void upCheck() {
        final String url = Constants.HTTP_GREEN_ADD; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        object.addProperty("gId", gId);
        object.addProperty("gName", gName);
        object.addProperty("ghProject", project);
        object.addProperty("ghUser", FoxContext.getInstance().getName());

        JsonArray bookArray = new JsonArray();

        if (checkList != null && checkList.size() != 0) {
            // 键和值
            String key = null;
            String value = null;
            // 获取键值对的迭代器
            Iterator it = checkList.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                value = (String) entry.getValue();
                key=(String) entry.getKey();
                JsonObject jsonObject1 = new JsonObject();
                Log.e("------","dddcheckList=="+checkList.size()+"==dddkey=="+key);
                jsonObject1.addProperty("gcId", key);
                jsonObject1.addProperty("gcName", value.split("-")[0]);
                        jsonObject1.addProperty("ghCyCleId", value.split("-")[1]);
                        jsonObject1.addProperty("ghCycle", value.split("-")[2]);
                bookArray.add(jsonObject1);
            }

        } else {
        }
        object.add("body", bookArray);
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("---------", "==fff===" + url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else {
                            Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = Constants.MESSAGE_UP;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    } else {
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NOT_NET;
                        mHandler.sendMessage(message);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     * @param listView
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        KMDMTBoxAdapter listAdapter = (KMDMTBoxAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

}
